// game.js
const app = getApp();

// 食物制作时间（毫秒）
const BASE_MAKING_TIME = {
  egg: 3000,
  bread: 4000,
  coffee: 2500
};

// 顾客耐心减少速度（每秒百分比）
const PATIENCE_DECREASE_RATE = 5;

// 顾客生成间隔（毫秒）
const CUSTOMER_GENERATION_INTERVAL = 5000;

// 最大顾客数量
const MAX_CUSTOMERS = 5;

// 食物价格
const FOOD_PRICES = {
  egg: 5,
  bread: 8,
  coffee: 6
};

Page({
  data: {
    userData: {
      coins: 0,
      level: 1,
      equipmentLevels: {
        egg: 1,
        bread: 1,
        coffee: 1
      }
    },
    customers: [],
    readyFoods: [],
    makingFood: {
      egg: false,
      bread: false,
      coffee: false
    },
    makingProgress: {
      egg: 0,
      bread: 0,
      coffee: 0
    },
    gameStatus: 'playing', // playing, paused, over
    currentScore: 0,
    earnedCoins: 0,
    customerIdCounter: 0,
    foodIdCounter: 0
  },

  onLoad: function() {
    // 从全局获取用户数据
    if (app.globalData.userData) {
      this.setData({
        'userData': app.globalData.userData
      });
    } else {
      // 初始化用户数据
      const initialUserData = {
        coins: 0,
        level: 1,
        equipmentLevels: {
          egg: 1,
          bread: 1,
          coffee: 1
        },
        highScore: 0
      };
      
      app.globalData.userData = initialUserData;
      this.setData({
        'userData': initialUserData
      });
      
      // 保存到云数据库
      app.updateUserData(initialUserData);
    }
  },

  onShow: function() {
    // 如果游戏状态是暂停，则恢复游戏
    if (this.data.gameStatus === 'paused') {
      this.resumeGame();
    } else if (!this.customerGenerationTimer) {
      // 初始化游戏
      this.startGame();
    }
  },

  onHide: function() {
    // 暂停游戏
    this.pauseGame();
  },

  onUnload: function() {
    // 清除所有定时器
    this.clearAllTimers();
  },

  startGame: function() {
    // 重置游戏状态
    this.setData({
      customers: [],
      readyFoods: [],
      makingFood: {
        egg: false,
        bread: false,
        coffee: false
      },
      makingProgress: {
        egg: 0,
        bread: 0,
        coffee: 0
      },
      gameStatus: 'playing',
      currentScore: 0,
      earnedCoins: 0,
      customerIdCounter: 0,
      foodIdCounter: 0
    });

    // 开始生成顾客
    this.startGeneratingCustomers();
    
    // 开始顾客耐心计时器
    this.startPatienceTimer();
  },

  pauseGame: function() {
    // 暂停所有定时器
    this.clearAllTimers();
    
    // 更新游戏状态
    this.setData({
      gameStatus: 'paused'
    });
  },

  resumeGame: function() {
    // 恢复游戏状态
    this.setData({
      gameStatus: 'playing'
    });
    
    // 重新启动定时器
    this.startGeneratingCustomers();
    this.startPatienceTimer();
    
    // 恢复正在制作的食物
    const { makingFood } = this.data;
    for (const food in makingFood) {
      if (makingFood[food]) {
        this.continueMakingFood(food);
      }
    }
  },

  gameOver: function() {
    // 清除所有定时器
    this.clearAllTimers();
    
    // 计算获得的金币
    const earnedCoins = Math.floor(this.data.currentScore / 2);
    
    // 更新用户数据
    const userData = this.data.userData;
    userData.coins += earnedCoins;
    
    // 更新最高分
    if (this.data.currentScore > (userData.highScore || 0)) {
      userData.highScore = this.data.currentScore;
    }
    
    // 更新数据
    this.setData({
      gameStatus: 'over',
      earnedCoins,
      userData
    });
    
    // 保存用户数据
    app.updateUserData(userData);
  },

  restartGame: function() {
    this.startGame();
  },

  goToShop: function() {
    wx.switchTab({
      url: '/pages/shop/shop'
    });
  },

  startGeneratingCustomers: function() {
    // 清除之前的定时器
    if (this.customerGenerationTimer) {
      clearInterval(this.customerGenerationTimer);
    }
    
    // 设置定时器，定期生成顾客
    this.customerGenerationTimer = setInterval(() => {
      this.generateCustomer();
    }, CUSTOMER_GENERATION_INTERVAL);
    
    // 立即生成第一个顾客
    this.generateCustomer();
  },

  generateCustomer: function() {
    // 如果已经达到最大顾客数量，则不再生成
    if (this.data.customers.length >= MAX_CUSTOMERS) {
      return;
    }
    
    // 生成顾客的订单（1-3个食物）
    const orderCount = Math.floor(Math.random() * 3) + 1;
    const foodTypes = ['egg', 'bread', 'coffee'];
    const order = [];
    
    for (let i = 0; i < orderCount; i++) {
      const randomIndex = Math.floor(Math.random() * foodTypes.length);
      order.push(foodTypes[randomIndex]);
    }
    
    // 生成顾客
    const customer = {
      id: this.data.customerIdCounter,
      avatarIndex: Math.floor(Math.random() * 6) + 1, // 假设有6种顾客头像
      order,
      patience: 100, // 耐心值，从100%开始
      position: this.data.customers.length * 150, // 顾客的位置
      served: false,
      leaving: false
    };
    
    // 更新数据
    this.setData({
      customers: [...this.data.customers, customer],
      customerIdCounter: this.data.customerIdCounter + 1
    });
  },

  startPatienceTimer: function() {
    // 清除之前的定时器
    if (this.patienceTimer) {
      clearInterval(this.patienceTimer);
    }
    
    // 设置定时器，定期减少顾客的耐心
    this.patienceTimer = setInterval(() => {
      const { customers } = this.data;
      
      if (customers.length === 0) {
        return;
      }
      
      // 更新每个顾客的耐心值
      const updatedCustomers = customers.map(customer => {
        if (customer.served || customer.leaving) {
          return customer;
        }
        
        // 减少耐心值
        const newPatience = Math.max(0, customer.patience - PATIENCE_DECREASE_RATE);
        
        // 如果耐心值为0，顾客离开
        if (newPatience === 0 && !customer.leaving) {
          this.handleCustomerLeaving(customer.id);
        }
        
        return {
          ...customer,
          patience: newPatience
        };
      });
      
      this.setData({
        customers: updatedCustomers
      });
    }, 1000); // 每秒更新一次
  },

  handleCustomerLeaving: function(customerId) {
    const { customers } = this.data;
    
    // 找到对应的顾客
    const customerIndex = customers.findIndex(c => c.id === customerId);
    if (customerIndex === -1) {
      return;
    }
    
    // 标记顾客为离开状态
    const updatedCustomers = [...customers];
    updatedCustomers[customerIndex] = {
      ...updatedCustomers[customerIndex],
      leaving: true
    };
    
    this.setData({
      customers: updatedCustomers
    });
    
    // 一段时间后移除顾客
    setTimeout(() => {
      this.removeCustomer(customerId);
      
      // 如果没有顾客了，游戏结束
      if (this.data.customers.length === 0 && this.data.gameStatus === 'playing') {
        this.gameOver();
      }
    }, 500);
  },

  removeCustomer: function(customerId) {
    const { customers } = this.data;
    
    // 移除顾客
    const updatedCustomers = customers.filter(c => c.id !== customerId);
    
    // 更新剩余顾客的位置
    for (let i = 0; i < updatedCustomers.length; i++) {
      updatedCustomers[i].position = i * 150;
    }
    
    this.setData({
      customers: updatedCustomers
    });
  },

  makeFood: function(e) {
    const foodType = e.currentTarget.dataset.food;
    
    // 如果已经在制作中，则不重复制作
    if (this.data.makingFood[foodType]) {
      return;
    }
    
    // 开始制作食物
    this.setData({
      [`makingFood.${foodType}`]: true,
      [`makingProgress.${foodType}`]: 0
    });
    
    // 计算制作时间（根据设备等级减少时间）
    const equipmentLevel = this.data.userData.equipmentLevels[foodType];
    const makingTime = BASE_MAKING_TIME[foodType] * (1 - (equipmentLevel - 1) * 0.1);
    
    // 设置进度更新定时器
    const progressInterval = 50; // 每50毫秒更新一次进度
    const progressStep = 100 / (makingTime / progressInterval);
    
    this.foodProgressTimer = setInterval(() => {
      const currentProgress = this.data.makingProgress[foodType];
      const newProgress = Math.min(100, currentProgress + progressStep);
      
      this.setData({
        [`makingProgress.${foodType}`]: newProgress
      });
      
      // 如果进度达到100%，完成制作
      if (newProgress >= 100) {
        clearInterval(this.foodProgressTimer);
        this.finishMakingFood(foodType);
      }
    }, progressInterval);
  },

  continueMakingFood: function(foodType) {
    // 继续制作食物（恢复游戏时调用）
    const currentProgress = this.data.makingProgress[foodType];
    const remainingProgress = 100 - currentProgress;
    
    // 计算剩余时间
    const equipmentLevel = this.data.userData.equipmentLevels[foodType];
    const totalMakingTime = BASE_MAKING_TIME[foodType] * (1 - (equipmentLevel - 1) * 0.1);
    const remainingTime = totalMakingTime * (remainingProgress / 100);
    
    // 设置进度更新定时器
    const progressInterval = 50; // 每50毫秒更新一次进度
    const progressStep = 100 / (totalMakingTime / progressInterval);
    
    this.foodProgressTimer = setInterval(() => {
      const currentProgress = this.data.makingProgress[foodType];
      const newProgress = Math.min(100, currentProgress + progressStep);
      
      this.setData({
        [`makingProgress.${foodType}`]: newProgress
      });
      
      // 如果进度达到100%，完成制作
      if (newProgress >= 100) {
        clearInterval(this.foodProgressTimer);
        this.finishMakingFood(foodType);
      }
    }, progressInterval);
  },

  finishMakingFood: function(foodType) {
    // 重置制作状态
    this.setData({
      [`makingFood.${foodType}`]: false,
      [`makingProgress.${foodType}`]: 0
    });
    
    // 添加到已制作食物列表
    const newFood = {
      id: this.data.foodIdCounter,
      type: foodType
    };
    
    this.setData({
      readyFoods: [...this.data.readyFoods, newFood],
      foodIdCounter: this.data.foodIdCounter + 1
    });
    
    // 添加动画效果
    wx.vibrateShort({
      type: 'light'
    });
  },

  serveFood: function(e) {
    const foodId = e.currentTarget.dataset.id;
    const foodType = e.currentTarget.dataset.type;
    
    // 查找需要这种食物的顾客
    const { customers } = this.data;
    let customerToServe = null;
    let customerIndex = -1;
    
    for (let i = 0; i < customers.length; i++) {
      const customer = customers[i];
      if (!customer.served && !customer.leaving && customer.order.includes(foodType)) {
        customerToServe = customer;
        customerIndex = i;
        break;
      }
    }
    
    // 如果没有找到需要这种食物的顾客，不做任何操作
    if (!customerToServe) {
      return;
    }
    
    // 从已制作食物列表中移除
    const { readyFoods } = this.data;
    const updatedReadyFoods = readyFoods.filter(food => food.id !== foodId);
    
    // 从顾客订单中移除这种食物
    const updatedOrder = customerToServe.order.filter(item => item !== foodType);
    
    // 更新顾客数据
    const updatedCustomers = [...customers];
    updatedCustomers[customerIndex] = {
      ...customerToServe,
      order: updatedOrder,
      served: updatedOrder.length === 0 // 如果订单为空，标记为已服务完成
    };
    
    // 计算得分和金币
    const score = Math.ceil(FOOD_PRICES[foodType] * (customerToServe.patience / 100));
    const currentScore = this.data.currentScore + score;
    
    // 更新数据
    this.setData({
      customers: updatedCustomers,
      readyFoods: updatedReadyFoods,
      currentScore
    });
    
    // 如果顾客已经服务完成，一段时间后让顾客离开
    if (updatedOrder.length === 0) {
      setTimeout(() => {
        this.handleCustomerLeaving(customerToServe.id);
      }, 1000);
    }
    
    // 添加动画效果
    wx.vibrateShort({
      type: 'light'
    });
  },

  clearAllTimers: function() {
    // 清除所有定时器
    if (this.customerGenerationTimer) {
      clearInterval(this.customerGenerationTimer);
      this.customerGenerationTimer = null;
    }
    
    if (this.patienceTimer) {
      clearInterval(this.patienceTimer);
      this.patienceTimer = null;
    }
    
    if (this.foodProgressTimer) {
      clearInterval(this.foodProgressTimer);
      this.foodProgressTimer = null;
    }
  }
});